<template>
  <el-dialog
    v-el-drag-dialog
    title="库存预警"
    :visible.sync="visible"
    width="90%"
    @closed="reset"
  >
    <div class="store-warning">
      <el-input v-model="goodsName" placeholder="请输入商品名称" style="width: 400px;">
        <el-button slot="append" icon="el-icon-search" />
      </el-input>
      <div class="goods-list">
        <aside-tree
          title="商品分类"
          :mouse-button="false"
          :tree-data="treeData"
          :loading="$loadingPlugin.getTreeData"
          @currentChange="currentChange"
          @refresh="getTreeData"
        />
        <div class="table-container">
          <lb-table
            ref="lbTable1"
            v-loading="$loadingPlugin.fetchData"
            border
            element-loading-text="加载中"
            :column="tableData.column"
            :data="tableData.data"
            :height="500"
            :immediate-fetch="false"
            table-key="goodsId"
            @fetch="fetchData"
            @selection-change="handleSelectionChange"
          />
        </div>
        <div class="selected-table">
          <lb-table
            ref="lbTable2"
            border
            :column="selectTableData.column"
            :data="selectTableData.data"
            :height="500"
            table-key="id"
          />
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import AsideTree from '../../../components/GoodsTypeTree'
  import { goodsTypeQueryList, queryGoodsList, querySpecList, querySaveStoreWarning, queryDefaultStoreWarningList } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { formatColumnMap } from '@/utils'

  export default {
    name: 'StoreWarning',
    components: {
      AsideTree
    },
    data() {
      return {
        visible: false,
        setDefault: false,
        goodsName: '',
        multipleSelection: [],
        treeData: [],
        specList: [], // 商品型号列表
        gtId: 0, // 商品类型id
        storeId: '',
        tableData: {
          total: 0,
          column: [
            {
              type: 'selection',
              width: 50
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 200
            },
            {
              prop: 'specCode',
              label: '规格型号',
              width: 80,
              render: (h, { row }) => <span>{ row.specCode && formatColumnMap(this.specList, 'specCode', row.specCode, 'specName') }</span>
            },
            {
              prop: 'unitName',
              label: '单位',
              width: 50
            }
          ],
          data: []
        },
        selectTableData: {
          total: 0,
          column: [
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 200
            },
            {
              prop: 'specCode',
              label: '规格型号',
              width: 80,
              render: (h, { row }) => <span>{ row.specCode && formatColumnMap(this.specList, 'specCode', row.specCode, 'specName') }</span>
            },
            {
              prop: 'unitName',
              label: '单位',
              width: 50
            },
            {
              prop: 'stockHighWarn',
              width: 100,
              label: '高位预警值',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <el-input-number size='small' controls={false} value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val }} min={1} max={9999} precision={0} controls-position='right'></el-input-number>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              prop: 'stockLowWarn',
              width: 100,
              label: '低位预警值',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <el-input-number size='small' controls={false} value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val }} min={1} max={9999} precision={0} controls-position='right'></el-input-number>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              prop: 'fillCount',
              width: 100,
              label: '补仓数量',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <el-input-number size='small' controls={false} value={ scope.row[scope.column.property] } onInput={ (val) => { scope.row[scope.column.property] = val }} min={1} max={9999} precision={0} controls-position='right'></el-input-number>
                        : <span>{ scope.row[scope.column.property] }</span>
                    }
                  </div>
                )
              }
            },
            {
              label: '操作',
              width: 140,
              alignt: 'center',
              fixed: 'right',
              render: (h, scope) => {
                return (
                  <div>
                    {
                      scope.row._edit
                        ? <div>
                          <el-button type='primary' onClick={ () => { this.handleSave(scope) } }>保存</el-button>
                          <el-button onClick={ () => { this.handleDel(scope) } }>删除</el-button>
                        </div>
                        : <div>
                          <el-button type='primary' onClick={ () => { this.handleEdit(scope) } }>编辑</el-button>
                          <el-button onClick={ () => { this.handleDel(scope) } }>删除</el-button>
                        </div>
                    }
                  </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    methods: {
      async open(temp) {
        await Promise.all([this.getTreeData(), this.getDefaultTableData(temp)])
        this.storeId = temp.storeId
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      async getDefaultTableData(temp) {
        const res = await queryDefaultStoreWarningList({ storeId: temp.storeId })
        this.selectTableData.data = res.data
        this.selectTableData.defaultData = JSON.parse(JSON.stringify(res.data))
        console.log(this.selectTableData.data, 123)
      },
      // 获取树图数据
      async getTreeData() {
        const res = await goodsTypeQueryList({})
        const data = res.data.map(item => ({
          label: item.gtName,
          ...item
        }))
        this.treeData = getTreeData(data, null, 'gtId')
      },
      async fetchData() {
        const query = {
          gtId: this.gtId,
          goodsName: '',
          currentPage: 1,
          pageSize: 9999
        }
        const res = await queryGoodsList(query)
        this.tableData.data = res.data.rows
        console.log(this.setDefault, this.selectTableData)
        const copy = JSON.parse(JSON.stringify(this.tableData.data))
        this.$nextTick(() => {
          if (!this.setDefault && this.selectTableData.data.length > 0) {
            this.selectTableData.data.forEach(item => {
              console.log(item, 111111, this.$refs)
              // const index = this.tableData.data.findIndex(it => it.goodsId === item.goodsId)
              copy.forEach(it => {
                if (it.goodsId === item.goodsId) {
                  it.stockHighWarn = item.stockHighWarn
                  it.stockLowWarn = item.stockLowWarn
                  it.fillCount = item.fillCount
                }
              })
              console.log(copy, 222)
              // copy[index].stockHighWarn = item.stockHighWarn
              // copy[index].stockLowWarn = item.stockLowWarn
              // copy[index].fillCount = item.fillCount
              this.$set(this.tableData, 'data', copy)
              // this.$refs.lbTable1.toggleRowSelection(this.tableData.data[index])
            })
            this.setDefault = true
          }
        })
      },
      // 选择变化
      currentChange(current) {
        this.gtId = current.gtId
        this.fetchData()
        this.getSpecName(current.gtId)
      },
      async getSpecName(gtId) {
        const res = await querySpecList({ gtId, currentPage: 1, pageSize: 9999 })
        this.specList = res.data.rows
      },
      // 勾选商品
      handleSelectionChange(val) {
        console.log(val, 888)
        this.multipleSelection = val
        this.selectTableData.defaultData = JSON.parse(JSON.stringify(val))
        this.$set(this.selectTableData, 'data', val)
      },
      handleEdit(scope) {
        this.$set(scope.row, '_edit', true)
      },
      handleSave(scope) {
        if (!scope.row.stockHighWarn || !scope.row.stockLowWarn || !scope.row.fillCount) {
          this.$message.warning('请填写完整')
          return
        }
        this.$set(scope.row, '_edit', false)
        this.$set(this.selectTableData.defaultData, scope.$index, JSON.parse(JSON.stringify(scope.row)))
      },
      handleDel(scope) {
        this.selectTableData.data.splice(scope.$index, 1)
        this.$refs.lbTable1.toggleRowSelection(scope.row)
      },
      async success() {
        if (this.selectTableData.data.length === 0) {
          this.$message.warning('请添加商品')
          return
        }
        if (this.selectTableData.data.some(item => !item.stockHighWarn || !item.stockLowWarn || !item.fillCount)) {
          this.$message.warning('信息不完整，请填写')
          return
        }
        const copy = JSON.parse(JSON.stringify(this.selectTableData.data))
        copy.forEach(item => {
          item._edit = false
        })
        this.$set(this.selectTableData, 'data', copy)
        const params = {
          storeId: this.storeId,
          warnList: this.selectTableData.data
        }
        await querySaveStoreWarning(params)
      },
      reset() {
        this.setDefault = false
        this.multipleSelection = []
        this.tableData.data = []
        this.selectTableData.data = []
        this.selectTableData.defaultData = []
      }
    }
  }
</script>

<style lang="scss" scoped>
.store-warning {
  height: 550px;
  .goods-list {
    display: flex;
    height: 500px;
    margin-top: 5px;
    .table-container {
      width: 380px;
    }
    .selected-table {
      margin-left: 10px;
      overflow: auto;
      flex: 1;
      /deep/ .el-input-number.is-without-controls .el-input__inner {
        width: 80px;
        padding-right: 5px;
        padding-left: 5px;
      }
    }
  }
}
.aside.open {
  width: 200px;
}
</style>
